"use client";
import React, { useEffect, useRef, useState } from "react";
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { Input, Button, Spin } from "antd";
import { SendOutlined, LeftOutlined, SettingOutlined } from "@ant-design/icons";
import Markdown from "react-markdown";
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { dark } from "react-syntax-highlighter/dist/esm/styles/prism";
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';

interface Message {
  content: string;
  isUser: boolean;
  timestamp: Date;
  role: string;
}

export default function Chat() {
  const [messages, setMessages] = useState<Message[]>([
    {
      content: "你好，我是AI助手。请问有什么可以帮助您的吗？",
      isUser: false,
      timestamp: new Date(),
      role: "system",
    },
  ]);
  const [inputValue, setInputValue] = useState("");
  const chatWindowRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(false);
  const accumulatedContentRef = useRef(""); // 使用 useRef 存储累积内容
  const [currentAiMsg, setCurrentAiMsg] = useState<string>("");

  useEffect(() => {
    if (chatWindowRef.current) {
      chatWindowRef.current.scrollTop = chatWindowRef.current.scrollHeight;
    }
  }, [messages]);

  const handleSend = () => {
    if (inputValue.trim()) {
      setInputValue("");
      setLoading(true);
      setCurrentAiMsg("");
      accumulatedContentRef.current = ""; // 重置累积内容
      // 调用 chat 方法
      chat(inputValue);
    }
  };

  const chat = async (inputValue: string) => {
    const ctrlAbout = new AbortController();
    const { signal } = ctrlAbout;
    
    messages.push(
      {
        content: inputValue,
        isUser: true,
        timestamp: new Date(),
        role: "user",
      },
      {
        content: "",
        isUser: false,
        timestamp: new Date(),
        role: "assistant",
      }
    );

    fetchEventSource("http://10.100.153.107:8002/api/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "text/event-stream",
      },
      body: JSON.stringify(messages),
      signal,
      onmessage(event) {
        if (event.data === "[DONE]") {
          // 如果接收到结束标记，停止累积
          return;
        }


        try {
          const data = JSON.parse(event.data); // 解析接收到的数据
          console.log(data.content,'event.data.content ===>',data.content.includes("\n"))
          let newContent = data.content || ""; // 获取新生成的内容
          if (newContent.includes("\n")) {
            newContent = "：\n\n"
          }

          if (newContent.trim() !== "") {
            accumulatedContentRef.current += newContent; // 累积内容
            setCurrentAiMsg((pre) => (pre += newContent));
          }
        } catch (error) {
          console.error("Error parsing event data:", error);
        }
      },
      onclose() {
        // 流关闭后，确保最后一条消息已正确显示
        setMessages((prevMessages) => {
          const updatedMessages = [...prevMessages];
          updatedMessages[updatedMessages.length - 1].content =
            accumulatedContentRef.current;
          return updatedMessages;
        });
        setLoading(false);
      },
      onerror(error) {
        console.error("Stream error:", error);
        setLoading(false);
      },
    });
  };

  console.log(messages);
  console.log(accumulatedContentRef,'accumulatedContentRef===>')

  return (
    <div className="flex flex-col h-full bg-gray-20">
      {/* Header */}
      <header className="bg-white shadow-md p-4 flex items-center justify-between">
        <button className="text-gray-600 hover:text-gray-800">
          <LeftOutlined className="text-xl" />
        </button>
        <h1 className="text-xl font-semibold text-gray-800">AI助手</h1>
        <button className="text-gray-600 hover:text-gray-800">
          <SettingOutlined className="text-xl" />
        </button>
      </header>

      {/* Chat Window */}
      <div
        ref={chatWindowRef}
        className="flex-1 overflow-y-auto p-4 space-y-4"
        style={{
          backgroundImage:
            "url(https://mastergo.com/ai/api/search-image?query=abstract soft gradient background with light blue and white colors, subtle patterns, creating a soothing and modern atmosphere for a chat application&width=1440&height=1024&orientation=landscape&flag=6b80639d405f71ba22f0667f2ffd3fba)",
          backgroundSize: "cover",
          backgroundPosition: "center",
        }}
      >
        {messages.map((message, index) => (
          <div
            key={index}
            className={`flex ${
              message.isUser ? "justify-end" : "justify-start"
            }`}
          >
            <div
              className={`max-w-xs sm:max-w-md md:max-w-lg lg:max-w-xl xl:max-w-2xl rounded-lg p-3 ${
                message.isUser
                  ? "bg-blue-500 text-white"
                  : "bg-white text-black"
              }`}
            >
              <Markdown
                components={{
                  code(props) {
                    const { children, className, ...rest } = props;
                    
                    const match = /language-(\w+)/.exec(className || "");
                    console.log(currentAiMsg,'currentAiMsg ===>');
                    console.log(match,'match ===>');
                    console.log(children,'children ===>');
                    console.log(className,'className ===>');

                    return match ? (
                      <SyntaxHighlighter
                        {...rest}
                        PreTag="div"
                        language={match[1]}
                        style={docco}
                        ref={props.ref as React.Ref<SyntaxHighlighter>}
                      >
                        {String(children).replace(/\n$/, '')}
                      </SyntaxHighlighter>
                    ) : (
                      <code {...rest} className={className}>
                        {children}
                      </code>
                    );
                  },
                }}
              >
                {index === messages.length - 1 && currentAiMsg
                  ? currentAiMsg
                  : message.content}
              </Markdown>
              <p className="text-xs mt-1 text-gray-300">
                {message.timestamp.toLocaleTimeString()}
              </p>
            </div>
          </div>
        ))}
        {loading && (
          <div className="flex justify-start">
            <div className="bg-white text-gray-800 rounded-lg p-3">
              <Spin size="small" />
              <span className="ml-2">AI正在思考中...</span>
            </div>
          </div>
        )}
      </div>

      {/* Input Area */}
      <div className="bg-white p-4 shadow-lg">
        <div className="flex items-center space-x-2">
          <Input
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onPressEnter={handleSend}
            placeholder="输入您的问题..."
            className="flex-1 text-sm"
            style={{ boxShadow: "inset 0 0 0 1px #e2e8f0" }}
          />
          <Button
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSend}
            className="!rounded-button whitespace-nowrap"
          >
            发送
          </Button>
        </div>
      </div>
    </div>
  );
}
